//
//  DestinationsResultViewController.m
//  TripGo
//
//  Created by dllo on 15/7/18.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "DestinationsResultViewController.h"
#import "AFNetworkHandler.h"
#import "DestinationResultCollectionViewCell.h"
#import "TravelViewController.h"
#import "UIViewController+Example.h"
#import "Destination.h"
#import "MJRefresh.h"
#import "DestinationsResultPushViewController.h"

static int page = 1;
@interface DestinationsResultViewController () <UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@end

@implementation DestinationsResultViewController
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
//自己创建视图控制器的时候的初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if ([super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        //通知的注册一般放在初始化中
        [self createNoCenter];
    }
    return self;
}
#pragma mark - NotificationCenter 通知中心
- (void)createNoCenter
{
    //通知中心单例 (在任何地方使用的通知中心都是同一个)
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //注册通知
    [center addObserver:self selector:@selector(chuanzhi:) name:@"passStr" object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"title.jpg"] forBarMetrics:UIBarMetricsDefault];
    for (UIView *aview in self.navigationController.navigationBar.subviews) {
        if ([aview.class isEqual:[UISearchBar class]]) {
            aview.hidden = _isHiden;
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    [self createCollectionView];
    [self getData:page where:nil];
    [self exampleUpPush];
    [self exampleDownPush];

    // Do any additional setup after loading the view.
}
- (void)chuanzhi:(NSNotification *)notification
{
    self.name = notification.object;
    // 定义菊花控件
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:self.activityIndicator];
    self.activityIndicator.color = [UIColor grayColor];
    self.activityIndicator.center = self.view.center;
    [_activityIndicator release];
    [self.activityIndicator startAnimating];
    [self getData:1 where:@"downPush"];
}
- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    //设置头部区域
    layout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, 30);
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:[DestinationResultCollectionViewCell class] forCellWithReuseIdentifier:@"ccCell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    self.collectionView.contentInset = UIEdgeInsetsMake(-30, 0, 100, 0);
    [_collectionView release];
}
- (void)getData:(int)page where:(NSString *)where;
{
    NSString *strPush = [NSString stringWithFormat:@"http://chanyouji.com/api/search/attractions.json?q=%@&page=%d", self.name, page];
    [AFNetworkHandler GetWithAFNByURL:strPush completion:^(id result) {
        NSArray *tempArr = result;
        //        if (tempArr.count == 0) {
        //            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有符合条件的结果" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        //            [al show];
        //            [al release];
        //            return;
        //        }
        NSMutableArray *temp = [NSMutableArray array];
        temp = [Destination arrayWithModelByArray:tempArr];
        if ([where isEqualToString:@"upPush"] == YES || [where isEqualToString:nil] == YES) {
            for (Destination *d in temp) {
                [self.arr addObject:d];
            }
            [self.collectionView reloadData];
            // 拿到当前的上拉刷新控件，结束刷新状态
            [self.collectionView.footer endRefreshing];
        } else if ([where isEqualToString:@"downPush"] == YES) {
            self.arr = [NSMutableArray array];
            for (NSInteger i = temp.count - 1; i >= 0 ; i--) {
                Destination *d = temp[i];
                [self.arr insertObject:d atIndex:0];
            }
            [self.collectionView reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.collectionView.header endRefreshing];
        }
        [self.activityIndicator stopAnimating];
    }];
    
}
- (void)exampleDownPush
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    self.collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
- (void)exampleUpPush
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
}
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    NSString *where = @"downPush";
    static int a = 1;
    [self getData:a where:where];
    page = 1;
}
- (void)loadMoreData
{
    // 1.向上拖动时page自加
    NSString *where = @"upPush";
    page++;
    [self getData:page where:where];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationsResultPushViewController *desRvc = [[DestinationsResultPushViewController alloc] init];
    desRvc.passId = [self.arr[indexPath.item] destiId].stringValue;
    _isHiden = NO;
    for (UIView *aview in self.navigationController.navigationBar.subviews) {
        if ([aview.class isEqual:[UISearchBar class]]) {
            aview.hidden = YES;
        }
    }
    [self.navigationController pushViewController:desRvc animated:YES];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(170, 150);
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationResultCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ccCell" forIndexPath:indexPath];
    cell.image.image = [UIImage imageNamed:@"ArticleCoverMask"];
    cell.des = self.arr[indexPath.item];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
